//
//  KChangePasswordViewController.m
//  KutulusLaw
//
//  Created by Mahmood1 on 12/19/12.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//

#import "KChangePasswordViewController.h"
#import "CCommon.h"
#import "KChangePasswordDAO.h"
#import "Constant.h"
#import "UserService.h"
#import "LoginViewController.h"

@implementation KChangePasswordViewController {
	UITextField *_oldPassword;
	UITextField *_newPassword;
	UITextField *_reNewPassword;
}

- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle
-(BOOL)checkRemember
{
	NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults];
	NSString *user = [userDefault objectForKey:@"username"];
	NSString *pass = [userDefault objectForKey:@"password"];
	if ([user length] != 0 && [pass length] != 0) {
		return YES;
	}
	else
		return NO;
}

-(void)back : (id) sender
{
    [self dismissModalViewControllerAnimated:YES];
}

- (void)save:(id) sender {
	if ([_oldPassword.text length] == 0 || [_newPassword.text length] == 0) {
		return;
	}
	
	if ([_newPassword.text length] < 6) {
		[[[UIAlertView alloc] initWithTitle: NSLocalizedString(@"Message", nil) message:NSLocalizedString(@"New password is more than 6 letters", nil) delegate:nil cancelButtonTitle: NSLocalizedString(@"OK", nil) otherButtonTitles:nil, nil] show];
		return;
	}
	
	if ([_oldPassword.text isEqualToString:[CCommon sharePassword]]) {
		if ([_newPassword.text isEqualToString:_reNewPassword.text]) {
			[_progressHUD show:YES];
			
			[KChangePasswordDAO changePassword:[CCommon shareSessionID] password:_newPassword.text block:^(NSInteger isSuccess, NSError *error) {
				[_progressHUD hide:YES];
				switch (isSuccess) {
					case OK:
						[CCommon setPasword:_newPassword.text];
						[[[UIAlertView alloc] initWithTitle:NSLocalizedString(@"Message", nil) message:NSLocalizedString(@"Change password is successful", nil) delegate:nil cancelButtonTitle:NSLocalizedString(@"OK", nil) otherButtonTitles:nil, nil] show];
						if ([self checkRemember]) {
							NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults];
							[userDefault setObject: _newPassword.text forKey:@"password"];
							[userDefault synchronize];
							
						}
						[self back:self];
						break;
					case NOT_AUTHENTICATE: {
						[_progressHUD show:YES];
						[UserService checkLoginWithUserName:[CCommon shareUsername] pass:[CCommon sharePassword] :^(id dictionary, NSError *error) {
							if (error) {
								UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"Message", nil) message: [error localizedDescription] delegate:nil cancelButtonTitle:NSLocalizedString(@"OK", nil) otherButtonTitles:nil, nil];
								[alert show];
								[_progressHUD hide:YES];
							}
							else
							{
								@try {
									
									if ([[dictionary objectForKey:@"status"] isEqualToString:@"OK"]) {
										[CCommon setSesionID: [dictionary objectForKey: kKEY_SESSION_ID]];
										[_progressHUD hide:YES];
										[self save:sender];
									}
									else
									{
										LoginViewController *login = [[LoginViewController alloc] init];
										login.navigationItem.hidesBackButton = YES;
										login.isFristLogin = NO;						
										[self.navigationController pushViewController:login animated:YES];
									}
								}
								@catch (NSException *exception) {
									[_progressHUD hide:YES];
								}
								@finally {
									//
								}
							}
						}];
					}
						break;
					case NOT_VALID:
						[[[UIAlertView alloc] initWithTitle: NSLocalizedString(@"Message", nil) message: NSLocalizedString(@"Change password is fail", nil) delegate:nil cancelButtonTitle: NSLocalizedString(@"OK", nil) otherButtonTitles:nil, nil] show];
						break;
					default:						
					
						break;
				}
			} ];
		} else {
			[[[UIAlertView alloc] initWithTitle:NSLocalizedString(@"Message", nil) message:NSLocalizedString(@"Password is not match", nil) delegate:nil cancelButtonTitle:NSLocalizedString(@"OK", nil) otherButtonTitles:nil, nil] show];
		}
		
	} else {
		[[[UIAlertView alloc] initWithTitle:NSLocalizedString(@"Message", nil) message: NSLocalizedString(@"Old password is wrong", nil) delegate:nil cancelButtonTitle:NSLocalizedString(@"OK", nil) otherButtonTitles:nil, nil] show];
	}
}

- (void)viewDidLoad
{
    [super viewDidLoad];

    // Uncomment the following line to preserve selection between presentations.
    // self.clearsSelectionOnViewWillAppear = NO;
 
    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
	self.navigationItem.hidesBackButton = YES;
	self.title = NSLocalizedString(@"Change Password", nil);
    UIButton *btnBack = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 41, 46)];
    btnBack.tintColor = [UIColor blackColor];
    [btnBack setImage:[UIImage imageNamed: kImageSetting34x46] forState:UIControlStateNormal];
    [btnBack setContentHorizontalAlignment:UIControlContentHorizontalAlignmentRight];
    [btnBack addTarget:self action:@selector(back:) forControlEvents:UIControlEventTouchDown];
    [self.navigationController.navigationBar addSubview:btnBack];
    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"nav-bg-black"] forBarMetrics:UIBarMetricsDefault] ;
	
	self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"bgback.png"]];
	self.tableView.backgroundView = nil;
	
    UIButton *btnLogout = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 67, 24)];
    [btnLogout setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
	
    [btnLogout setTitle:NSLocalizedString(@"Save", nil) forState:UIControlStateNormal];
    btnLogout.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"logout-67x24.png"]];
    btnLogout.titleLabel.font = [UIFont boldSystemFontOfSize:16.0f];
    btnLogout.titleLabel.textColor = [UIColor grayColor];
    [btnLogout addTarget:self action:@selector(save:) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:btnLogout];
	
	_progressHUD = [[MBProgressHUD alloc] initWithView:self.view];
	_progressHUD.taskInProgress = YES;
	_progressHUD.progress = 0.5;
    _progressHUD.dimBackground = YES;

}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
}

- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    // Return the number of rows in the section.
    return 3;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *CellIdentifier = @"Cell";
    
   UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
		cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    }
	
	switch (indexPath.row) {
		case 0:
			if (!_oldPassword) {
				_oldPassword = [[UITextField alloc] init];
				[_oldPassword setBorderStyle:UITextBorderStyleNone];
				_oldPassword.frame = CGRectMake(10, 10, 270, 40);
				_oldPassword.placeholder = NSLocalizedString(@"Old Password", nil);
				[_oldPassword setSecureTextEntry:YES];
				[_oldPassword setDelegate:self];
			}
			[cell.contentView addSubview:_oldPassword];
			break;
		case 1:
			if (!_newPassword) {
				_newPassword = [[UITextField alloc] initWithFrame:CGRectMake(10, 10, 270, 40)];_newPassword.placeholder = NSLocalizedString(@"New Password",nil);
				[_newPassword setBorderStyle:UITextBorderStyleNone];
				[_newPassword setSecureTextEntry:YES];
				[_newPassword setDelegate:self];
			}
			[cell.contentView addSubview:_newPassword];
			break;
		case 2:
			if (!_reNewPassword) {
				_reNewPassword = [[UITextField alloc] initWithFrame:CGRectMake(10, 10, 270, 40)];
				[_reNewPassword setBorderStyle:UITextBorderStyleNone];
				_reNewPassword.placeholder = NSLocalizedString(@"Confirm Password", nil);
				[_reNewPassword setSecureTextEntry:YES];
				[_reNewPassword setDelegate:self];
			}
			[cell.contentView addSubview:_reNewPassword];
			break;
		default:
			break;
	}
    
    // Configure the cell...
    
    return cell;
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
	return NSLocalizedString(@"Change Password", nil);
}
/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
    }   
    else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath
{
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

#pragma mark - Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
	[self.tableView deselectRowAtIndexPath:indexPath animated:YES];
    // Navigation logic may go here. Create and push another view controller.
    /*
     <#DetailViewController#> *detailViewController = [[<#DetailViewController#> alloc] initWithNibName:@"<#Nib name#>" bundle:nil];
     // ...
     // Pass the selected object to the new view controller.
     [self.navigationController pushViewController:detailViewController animated:YES];
     */
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
	if (textField) {
		[textField resignFirstResponder];
	}
	
	return YES;
}
@end
